# -*- coding: UTF-8 -*-
import template
import requests
import json
from token_cache.access_token import token_instance
from bean.hot_new import HotNew
from typing import List


def add_draft(content_source_url, all_news):
    types = [2, 3, 5]
    draft_title = ""
    draft_author = "王瑞峰"
    draft_digest = ""
    media_id = ""
    articles = []
    for new_type in types:
        type_hot_news = all_news[new_type]
        draft_content = ""
        for hot_new in type_hot_news:
            draft_title = hot_new.new_type
            draft_digest = hot_new.new_type
            media_id = hot_new.img_path
            draft_content = draft_content + "\n" + template.draft_add_template\
                .format(hot_new.app_id, hot_new.app_path, hot_new.type_id, hot_new.title, hot_new.excerpt)
        articles.append({
            "title": draft_title,
            "author": draft_author,
            "digest": draft_digest,
            "content": draft_content,
            "content_source_url": content_source_url,
            "thumb_media_id": media_id,
            "need_open_comment": 0,
            "only_fans_can_comment": 0
        })

    response = requests.post("https://api.weixin.qq.com/cgi-bin/draft/add?access_token=" + token_instance.access_token,
                             data=json.dumps({
                                 "articles": articles
                             }, ensure_ascii=False).encode('utf-8'), headers={"Content-Type": "application/json"})
    result = json.loads(response.content)
    if response.status_code != 200:
        print(response.status_code)
        return None
    if "errcode" in result:
        print(result["errcode"], result["errmsg"])
        return None
    print(result)
    return result["media_id"]

